<?php
/** ensure this file is being included by a parent file */
defined('_JEXEC') or die('Restricted access');


class HelpDeskHelperUser 
{
	/**
	 * Generate a random password
	 *
	 * @static
	 * @param	int		$length	Length of the password to generate
	 * @return	string			Random Password
	 * @since	1.5
	 */
	function genRandomPassword($length = 8)
	{
		$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$len = strlen($salt);
		$makepass = '';

		$stat = @stat(__FILE__);
		if(empty($stat) || !is_array($stat)) $stat = array(php_uname());

		mt_srand(crc32(microtime() . implode('|', $stat)));

		for ($i = 0; $i < $length; $i ++) {
			$makepass .= $salt[mt_rand(0, $len -1)];
		}

		return $makepass;
	}
	
	/**
	 * Returns userid if a user exists
	 *
	 * @param string The username to search on
	 * @return int The user id or 0 if not found
	 */
	function getUserId($username)
	{
		// Initialize some variables
		$db = HelpDeskConfig::getDBO();

		$query = 'SELECT id FROM #__users WHERE username = ' . $db->Quote( $username );
		$db->setQuery($query, 0, 1);
		return $db->loadResult();
	}
	
	/**
	 * 
	 * @param $string
	 * @return unknown_type
	 */
	function usernameExists( $string ) {
		$success = false;
		$database = HelpDeskConfig::getDBO();
		$string = $database->getEscaped($string);
		$query = "
			SELECT 
				*
			FROM 
				#__users
			WHERE 1
			AND 
				`username` = '{$string}'
			LIMIT 1
		";
		$database->setQuery($query);
		$result = $database->loadObject();
		if ($result) {
			$success = true;
		}
		return $success;	
	}

	/**
	 * 
	 * @param $string
	 * @return unknown_type
	 */
	function emailExists( $string ) {
		$success = false;
		$database = HelpDeskConfig::getDBO();
		$string = $database->getEscaped($string);
		$query = "
			SELECT 
				*
			FROM 
				#__users
			WHERE 1
			AND 
				`email` = '{$string}'
			LIMIT 1
		";
		$database->setQuery($query);
		$result = $database->loadObject();
		if ($result) {
			$success = true;
		}		
		return $success;		
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &createNewUser( $details, &$msg, $useractivation='0' ) 
	{
		global $mainframe;
		global $database, $acl;
		$success = false;

		// Get required system objects
		// $user 		= clone(HelpDeskConfig::getUser());
		$user 		= new mosUser( $database );
		// $config		=& JFactory::getConfig();
		// $authorize	=& JFactory::getACL();
		$authorize = $acl;

		// $usersConfig = &JComponentHelper::getParams( 'com_users' );

		// Initialize new usertype setting
		// $newUsertype = $usersConfig->get( 'new_usertype' );
		$newUsertype = "";
		if (!$newUsertype) { $newUsertype = 'Registered'; }

		// Bind the post array to the user object
		if (!$user->bind( $details )) {
			return $success;
		}

		// Set some initial user values
		$user->set('id', 0);
		$user->set('usertype', '');
		$user->set('gid', $authorize->get_group_id( $newUsertype, 'ARO' ) );

		$date = HelpDeskConfig::getDate();
		$user->set('registerDate', $date->toMySQL());

		// If user activation is turned on, we need to set the activation information
		$useractivation = '0';
		if ($useractivation == '1') {
			HelpDeskHelperUtility::import('joomla.user.helper');
			$user->set('activation', md5( HelpDeskHelperUser::genRandomPassword() ) );
			$user->set('block', '1');
		}

		// If there was an error with registration, set the message and display form
		if ( !$user->save() ) {
			$msg->message = $user->getError();
			return $success;
		}

		// Send registration confirmation mail
		HelpDeskHelperUser::_sendMail( $user, $details, $useractivation );
		
		return $user;
	}

	/**
	 * Returns yes/no
	 * @param array [username] & [password]
	 * @param mixed Boolean
	 * 
	 * @return array
	 */	
	function login( $credentials, $remember='', $return='' ) {
		global $mainframe;

		if (strpos( $return, 'http' ) !== false && strpos( $return, HelpDeskUrl::base() ) !== 0) {
			$return = '';
		}

		// $credentials = array();
		// $credentials['username'] = HelpDeskRequest::getVar('username', '', 'method', 'username');
		// $credentials['password'] = JRequest::getString('passwd', '', 'post', JREQUEST_ALLOWRAW);
		
		$options = array();
		$options['remember'] = $remember;
		$options['return'] = $return;

		//preform the login action
		$success = $mainframe->login($credentials, $options);

		if ( $return ) {
			$mainframe->redirect( $return );
		}
		
		return $success;
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @return array
	 */
	function logout( $return='' ) {
		global $mainframe;

		//preform the logout action
		$success = $mainframe->logout();

		if (strpos( $return, 'http' ) !== false && strpos( $return, HelpDeskUrl::base() ) !== 0) {
			$return = '';
		}

		if ( $return ) {
			$mainframe->redirect( $return );
		}
		
		return $success;		
	}

	/**
	 * Returns yes/no
	 * @param object
	 * @param mixed Boolean
	 * @return array
	 */
	function _sendMail( &$user, $details, $useractivation ) {
		global $mainframe;

		$db		=& HelpDeskConfig::getDBO();

		$name 		= $user->get('name');
		$email 		= $user->get('email');
		$username 	= $user->get('username');
		$activation	= $user->get('activation');
		$password 	= $details['password2']; // using the original generated pword for the email
		
		// $usersConfig 	= &JComponentHelper::getParams( 'com_users' );
		// $useractivation = $usersConfig->get( 'useractivation' );
		$sitename 		= $mainframe->getCfg( 'sitename' );
		$mailfrom 		= $mainframe->getCfg( 'mailfrom' );
		$fromname 		= $mainframe->getCfg( 'fromname' );
		$siteURL		= HelpDeskUrl::base();

		$subject 	= sprintf ( HelpDeskText::_( 'Account details for' ), $name, $sitename);
		$subject 	= html_entity_decode($subject, ENT_QUOTES);

		if ( $useractivation == 1 ){
			$message = sprintf ( HelpDeskText::_( 'Email Message Activation' ), $sitename, $siteURL, $email, $password, $activation );
		} else {
			$message = sprintf ( HelpDeskText::_( 'Email Message' ), $sitename, $siteURL, $email, $password );
		}

		$message = html_entity_decode($message, ENT_QUOTES);

		//get all super administrator
		$query = 'SELECT name, email, sendEmail' .
				' FROM #__users' .
				' WHERE LOWER( usertype ) = "super administrator"';
		$db->setQuery( $query );
		$rows = $db->loadObjectList();

		// Send email to user
		if ( ! $mailfrom  || ! $fromname ) {
			$fromname = $rows[0]->name;
			$mailfrom = $rows[0]->email;
		}

		$success = HelpDeskHelperUser::_doMail($mailfrom, $fromname, $email, $subject, $message);
		
		return $success;
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	function _doMail( $from, $fromname, $recipient, $subject, $body, $actions=NULL, $mode=NULL, $cc=NULL, $bcc=NULL, $attachment=NULL, $replyto=NULL, $replytoname=NULL ) 
	{
		$success = false;

		$message = HelpDeskHelperEmail::getMailer();
		$message->addRecipient( $recipient );
		$message->setSubject( $subject );
		$message->setBody( $body );
		$sender = array( $from, $fromname );
		$message->setSender($sender);
		$sent = $message->send();
		if ($sent == '1') {
			$success = true;
		}
		
		return $success;
	}

}